/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.domain.vo.TeachId;
import me.zhengjie.modules.system.mapper.*;
import me.zhengjie.modules.system.service.ChapterlearnrecordService;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.system.service.MyteachService;
import me.zhengjie.modules.system.domain.vo.MyteachQueryCriteria;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import me.zhengjie.utils.PageResult;

/**
* @description 服务实现
* @author shitou
* @date 2024-04-21
**/
@Service
@RequiredArgsConstructor
public class MyteachServiceImpl extends ServiceImpl<MyteachMapper, Myteach> implements MyteachService {

    private final MyteachMapper myteachMapper;

    private final UserMapper userMapper;

    private final TeachMapper teachMapper;

    private final ChapterlearnrecordMapper chapterlearnrecordMapper;

    private final TeachsubsectionMapper teachsubsectionMapper;

    private final TeachchapterMapper teachchapterMapper;
    @Override
    public PageResult<Myteach> queryAll(MyteachQueryCriteria criteria, Page<Object> page){
        return PageUtil.toPage(myteachMapper.findAll(criteria, page));
    }

    @Override
    public List<Myteach> queryAll(MyteachQueryCriteria criteria){
        return myteachMapper.findAll(criteria);
    }

    @Override
    public PageResult<Teach>getStudentTeach(MyteachQueryCriteria criteria, Page<Object> page){
        String name = criteria.getName();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",currentUser.getId());
        List<Myteach> list = myteachMapper.selectList(queryWrapper);

        List<Integer> teachIds = new ArrayList<>();
        for (Myteach myteach : list) {
            teachIds.add(myteach.getTeachId());
        }
        List<Teach> teachList = new ArrayList<>();

        //获取记录
        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.in("teachId",teachIds);
        queryWrapper2.eq("userId",currentUser.getId());
        queryWrapper2.groupBy("teachSubsectionId");
        List<Chapterlearnrecord> list1 = chapterlearnrecordMapper.selectList(queryWrapper2);
        List<TeachId> teachIdList = new ArrayList<>();
        for(Chapterlearnrecord chapterlearnrecord:list1){
            TeachId teachIdpart = new TeachId();
            teachIdpart.setTeachId(Math.toIntExact(chapterlearnrecord.getTeachId()));
            if(teachIdList.size() == 0){
                teachIdList.add(teachIdpart);
            }
            Integer status = 0;
            if(chapterlearnrecord.getTeachSubsectionId()!=null){
                for(TeachId teachId:teachIdList){
                    if(Math.toIntExact(teachId.getTeachId()) == chapterlearnrecord.getTeachId()){
                        if(teachId.getTeachSubsectionCount() == null){
                            teachId.setTeachSubsectionCount(1);

                        } else {
                            teachId.setTeachSubsectionCount(teachId.getTeachSubsectionCount()+1);

                        }

                        status = 1;
                    }
                }
            } else if(chapterlearnrecord.getTeachChapterId()!=null){

                for(TeachId teachId:teachIdList){


                    System.out.println(Math.toIntExact(teachId.getTeachId()) == chapterlearnrecord.getTeachId());
                    if(Math.toIntExact(teachId.getTeachId()) == chapterlearnrecord.getTeachId()){
                        if(teachId.getTeachChapterCount()==null){
                            teachId.setTeachChapterCount(1);

                        } else {
                            teachId.setTeachChapterCount(teachId.getTeachChapterCount()+1);
                        }


//                        teachId.setTeachSubsectionCount(teachId.getTeachSubsectionCount()+1);
                        status = 1;
                    }
                }
            }

            if(status == 0){
                teachIdList.add(teachIdpart);
            }

        }
        //获取教材章节
        QueryWrapper queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.in("teachId",teachIds);
        List<Teachchapter> teachchapterList = teachchapterMapper.selectList(queryWrapper3);
        for(Teachchapter teachchapter:teachchapterList){
            for(TeachId teachId:teachIdList){
                if(teachId.getTeachId().equals(teachchapter.getTeachid())){
                    if(teachId.getAllTeachChapterCount()!=null){
                        teachId.setAllTeachChapterCount(teachId.getAllTeachChapterCount()+1);

                    } else {
                        teachId.setAllTeachChapterCount(1);

                    }
                }
            }
        }

        QueryWrapper queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.in("teachId",teachIds);


        List<Teachsubsection> teachsubsectionList = teachsubsectionMapper.selectList(queryWrapper4);
        for(Teachsubsection teachsubsection:teachsubsectionList){
            for(TeachId teachId:teachIdList){
                if(Math.toIntExact(teachId.getTeachId()) == teachsubsection.getTeachid()){
                    if(teachId.getAllTeachSubsectionCount() == null){
                        teachId.setAllTeachSubsectionCount(1);

                    } else {
                        teachId.setAllTeachSubsectionCount(teachId.getAllTeachSubsectionCount()+1);

                    }
                }
            }
        }
//        List<Teach> resultTeach = result.getContent();

//System.out.println("=teachIdList="+teachIdList);
        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.in("id",teachIds);
        if(name != null && !name.equals("")){
            queryWrapper1.in("name",name);
        }

        PageResult<Teach> result = null;
        if(teachIds.size() == 0){
//            return teachList;
            result = PageUtil.toPage(teachList);
        } else {
            IPage currentPage =  new Page<>(page.getCurrent(), page.getSize());

            List<Teach> resultTeach = new ArrayList<>();
            IPage currentPageTeach  = teachMapper.selectPage(currentPage,queryWrapper1);
            resultTeach = currentPageTeach.getRecords();
            for(Teach teach:resultTeach){
                for(TeachId teachId:teachIdList){
                    if(teach.getId() == Math.toIntExact(teachId.getTeachId())){

                        Float current1 = (float) 0;
                        if(teachId.getTeachChapterCount() !=null && teachId.getAllTeachChapterCount()!=null){
                            current1 =  (teachId.getTeachChapterCount().floatValue()/teachId.getAllTeachChapterCount().floatValue());

                        }

                        Float current2 = (float) 0;
                        if(teachId.getTeachSubsectionCount() != null && teachId.getAllTeachSubsectionCount() != null){
                            current2 = (teachId.getTeachSubsectionCount().floatValue()/teachId.getAllTeachSubsectionCount().floatValue());

                        }

                        float current3 = current1+current2;
                        if(current3 != 0){
                            current3 = current3*100/2;
                        }
                        teach.setProgress(current3);
                    }
                }
            }
            currentPageTeach.setRecords(resultTeach);
            result = PageUtil.toPage(currentPageTeach);
//            return teachMapper.selectList(queryWrapper1);
        }
        List<Teach> teachList1 = new ArrayList<>();
//        List<Integer> teachIds2 = new ArrayList<>();
//        for(Teach teach:result.getContent()){
//            teachIds2.add(Math.toIntExact(teach.getId()));
//        }

//        result.setContent(resultTeach);
        return result;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Myteach resources) {
        save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Myteach resources) {
        Myteach myteach = getById(resources.getId());
        myteach.copy(resources);
        saveOrUpdate(myteach);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<Myteach> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Myteach myteach : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("教材id", myteach.getTeachId());
            map.put("用户id", myteach.getUserId());
            map.put(" lastupdatetime",  myteach.getLastupdatetime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}